package org.sith.taskrunner.gwt.client.presenter;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;
import org.sith.taskrunner.gwt.client.event.UserManageEvent;
import org.sith.taskrunner.gwt.client.resources.TaskRunnerMessages;
import org.sith.taskrunner.gwt.client.services.user.UsersManageGWTService;
import org.sith.taskrunner.gwt.client.view.IUserManageView;

public class UserManagePresenter implements TabPresenter,IUserManageView.Presenter{
    private HasWidgets container;
    private IUserManageView view;
    private EventBus eventBus;



    public UserManagePresenter(IUserManageView view,EventBus eventBus) {
        this.view = view;
        this.eventBus = eventBus;
        bind();
    }

    private void bind() {
    }

    @Override
    public void go(HasWidgets container) {
        this.container = container;
        this.container.add(view.getViewWidget());
    }

    @Override
    public void onSaveButtonClicked() {
        UsersManageGWTService.App.getInstance().addUser(view.getEditedObject(), new AsyncCallback<Void>() {
                    @Override
                    public void onFailure(Throwable caught) {
                        Window.alert("Can't add user: "+caught);
                        view.setResultLabel(true);
                    }

                    @Override
                    public void onSuccess(Void result) {
                        view.setResultLabel(true);
                        UserManageEvent event = new UserManageEvent();
                        event.setUser(view.getEditedObject());
                        event.setEventType(UserManageEvent.EventType.ADD_USER);
                        eventBus.fireEvent(event);

                    }
                });
    }

    @Override
    public void onRemoveButtonClicked() {
        UsersManageGWTService.App.getInstance().removeUser(view.getEditedObject(), new AsyncCallback<Void>() {
            @Override
            public void onFailure(Throwable caught) {
                Window.alert("Can't add user: " + caught);
                view.setResultLabel(true);
            }

            @Override
            public void onSuccess(Void result) {
                view.setResultLabel(true);
                UserManageEvent event = new UserManageEvent();
                event.setUser(view.getEditedObject());
                event.setEventType(UserManageEvent.EventType.REMOVE_USER);
                eventBus.fireEvent(event);

            }
        });
    }

    @Override
    public void onCancelButtonClicked() {
        view.restoreView();
    }


    @Override
    public String getTabTitle() {
        return TaskRunnerMessages.App.getInstance().manageUserLabel();
    }
}
